package mycoffee.order.task;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mycoffee.order.model.Table;
import mycoffee.order.utils.LogUtils;
import mycoffee.order.xmlhandler.TablesHandler;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.Context;

public class TablesTask extends AbstractTask<Void, Void, ArrayList<Table>> {
	private static final String TAG = "TablesTask";

	public TablesTask(Context context,
			IDataEventHandler<ArrayList<Table>> dataEventHandler) {
		super(context, dataEventHandler);
	}

	@Override
	protected ArrayList<Table> doExecute() {
		ArrayList<Table> result = null;
		// read food.xml file.
		InputStream stream = null;
		try {
			// read data from assets/forecast.xml.
			stream = mContext.getAssets().open("xml/tables.xml");

			if (!getShouldCancel() && stream != null) {
				SAXParserFactory spf = SAXParserFactory.newInstance();

				SAXParser sp;
				TablesHandler tablesHandler = new TablesHandler();

				try {
					sp = spf.newSAXParser();
					XMLReader xr = sp.getXMLReader();
					xr.setContentHandler(tablesHandler);
					xr.parse(new InputSource(stream));
					result = tablesHandler.getResult();
								

				} catch (ParserConfigurationException e) {
					LogUtils.logError(TAG, "ParserConfigurationException : "
							+ e.getMessage());
				} catch (SAXException e) {
					LogUtils.logError(TAG, "SAXException : " + e.getMessage());
				} catch (IOException e) {
					LogUtils.logError(TAG, "IOException : " + e.getMessage());
				}
			}
		} catch (IOException e) {
			//
		} finally {
			try {
				// close the stream.
				if (stream != null) {
					stream.close();
					stream = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

}
